package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Transactional(rollbackFor = Exception.class) //将删除方法交给spring管理事务(默认只运行异常回滚，加上Exception.class所有异常均回滚)
    @Override
    public void delete(List<Long> ids) {
        //判断当前菜品是否能够删除--是否存在起售中的菜品
        for (Long id : ids) {
            Dish dish=dishMapper.select(id);
            if(dish.getStatus()==1)
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }

        //判断当前菜品是否和套餐关联
        List<Long> setmealDishIds = setmealDishMapper.getSetmealDishIds(ids);
        if(setmealDishIds!=null||setmealDishIds.size()>0)
        {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品及其口味
        for (Long id : ids) {
            dishMapper.delete(id);
            dishFlavorMapper.delete(id);
        }

    }

    //新增菜品和对应的口味（操作两张表）
    @Transactional(rollbackFor = Exception.class) //将删除方法交给spring管理事务(默认只运行异常回滚，加上Exception.class所有异常均回滚)
    @Override
    public void insert(DishDTO dishDTO) {
        /*
            对象属性拷贝
         */
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setStatus(StatusConstant.ENABLE);
        dishMapper.Dishinsert(dish);

        /*
            这里需要将dish的id赋值给dishflavor，但是id设置为了自增，在数据库操作结束前这个id为空,mybatis默认不传回值
            如何操作？-->
            在mybatis xml文件中加入（<insert）useGeneratedKeys="true" keyProperty="id">这两个参数
         */
        Long id = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors!=null&&flavors.size()>0)
        {
            flavors.forEach(flavor->{
                flavor.setDishId(id);
            });
        }
        dishFlavorMapper.DishFlavorinsert(flavors);
    }

    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page=dishMapper.page(dishPageQueryDTO);
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }

    @Override
    public DishVO getById(Long id) {
        Dish dish = dishMapper.select(id);
        List<DishFlavor> list=dishFlavorMapper.select(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(list);
        return dishVO;
    }


    @Transactional(rollbackFor = Exception.class) //将删除方法交给spring管理事务(默认只运行异常回滚，加上Exception.class所有异常均回滚)
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);

        //先删掉原有的口味，再插入新更新的口味
        dishFlavorMapper.delete(dishDTO.getId());
        List<DishFlavor> flavors = dishDTO.getFlavors();
        /*
            非常容易忽视！！！ 在插入flavors表之前一定要判断是否为空并且大小是否大于0，否则插入空数据报错！！！
         */
        if(flavors!=null&&flavors.size()>0)
        {
            flavors.forEach(flavor->{
                flavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.DishFlavorinsert(flavors);
        }

    }

    public List<DishVO> listWithFlavor(Dish dish) {
        /*
            根据分类id查询这个分类内菜品信息
         */
        List<Dish> dishList = dishMapper.list(dish.getCategoryId());

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.select(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public List<Dish> selectByCategoryId(Long categoryId) {
        List<Dish> list=dishMapper.selectByCategoryId(categoryId);
        return list;
    }
}
